/**
 * router loader
 * @param {object} app koa 实例
 *  解析app/router/下面所有js文件，加载到 koaRouter 
 */

const path = require('path')
const { sep } = path;
const KoaRouter = require('@koa/router');
const { globSync} = require('glob');


module.exports = (app)=>{
        const router = new KoaRouter();
        // 读取文件
        const routerPath = path.resolve(app.businessPath, `.${sep}router`);
        const fileList = globSync(path.resolve(routerPath, `.${sep}**${sep}**.js`),{windowsPathsNoEscape:true});

        // 注册所有路由
        fileList.forEach(file=>{
            require(path.resolve(file))(app,router)
        })

        // 路由兜底
        router.get(/.*/,async(ctx,next)=>{
            ctx.state = 302;
            ctx.redirect(app?.options?.homePage ?? '/')
        })
        // 路由注册到 app 上
        app.use(router.routes());
        app.use(router.allowedMethods());
        

}